package com.lkd.service.impl;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyChannel;
import com.lkd.contract.SupplyContract;
import com.lkd.contract.TaskCompleteContract;
import com.lkd.dao.TaskDao;
import com.lkd.emq.MqttProducer;
import com.lkd.entity.TaskDetailsEntity;
import com.lkd.entity.TaskEntity;
import com.lkd.exception.LogicException;
import com.lkd.feign.UserService;
import com.lkd.feign.VMService;
import com.lkd.http.vo.CancelTaskViewModel;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskDetailsService;
import com.lkd.service.TaskService;
import com.lkd.vo.Pager;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.framework.adapter.ThrowsAdviceInterceptor;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.stream.Task;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class TaskServiceImpl extends ServiceImpl<TaskDao,TaskEntity> implements TaskService{

    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private VMService vMService;
    @Resource
    private UserService userService;
    @Resource
    private TaskDetailsService taskDetailsService;
    @Resource
    private MqttProducer mqttProducer;

    @Override
    public Pager<TaskEntity> search(Long pageIndex, Long pageSize, String innerCode, Integer userId, String taskCode, Integer status, Boolean isRepair, String start, String end) {
        Page<TaskEntity> page = new Page<>(pageIndex,pageSize);
        LambdaQueryWrapper<TaskEntity> qw = new LambdaQueryWrapper<>();
        if(!Strings.isNullOrEmpty(innerCode)){
            qw.eq(TaskEntity::getInnerCode,innerCode);
        }
        if(userId != null && userId > 0){
            qw.eq(TaskEntity::getUserId,userId);
        }
        if(!Strings.isNullOrEmpty(taskCode)){
            qw.like(TaskEntity::getTaskCode,taskCode);
        }
        if(status != null && status > 0){
            qw.eq(TaskEntity::getTaskStatus,status);
        }
        if(isRepair != null){
            if(isRepair){
                qw.ne(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
            }else {
                qw.eq(TaskEntity::getProductTypeId,VMSystem.TASK_TYPE_SUPPLY);
            }
        }
        if(!Strings.isNullOrEmpty(start) && !Strings.isNullOrEmpty(end)){
            qw
                    .ge(TaskEntity::getCreateTime, LocalDate.parse(start, DateTimeFormatter.ISO_LOCAL_DATE))
                    .le(TaskEntity::getCreateTime,LocalDate.parse(end,DateTimeFormatter.ISO_LOCAL_DATE));
        }
        //根据最后更新时间倒序排序
        qw.orderByDesc(TaskEntity::getUpdateTime);

        return Pager.build(this.page(page,qw));
    }

    /**
     * 创建工单
     * @param taskVo
     * @param
     * @return
     */
    @Override
    @Transactional
    public Boolean saveTask(TaskViewModel taskVo) throws LogicException {
        //检验工单是否合法
        VmVO vmInfo = checkTask(taskVo);

        //判断当前机器,是否有同类型,未完成的工单 --> task_status<=2
        //1.1获取机器编号
        String innerCode = taskVo.getInnerCode();
        //1.2获取工单类型id
        int productType = taskVo.getProductType();
        if(haveTask(innerCode,productType)){
            throw new LogicException("该机器下已有同类型工单,请勿重复发布");
        }


        TaskEntity taskEntity = new TaskEntity();
        BeanUtils.copyProperties(taskVo,taskEntity);

        //设置工单编号
        taskEntity.setTaskCode(this.createTaskCode());
        //工单状态
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_CREATE);
        //执行人名称
        taskEntity.setUserName(userService.getUser(taskVo.getUserId()).getUserName());
        //工单类型id
        taskEntity.setProductTypeId(taskVo.getProductType());
        //指派人id
        taskEntity.setAssignorId(taskVo.getAssignorId());

        //点位地址---feign调用机器服务,根据机器编号查询到机器的地址和区域id
        taskEntity.setAddr(vmInfo.getNodeAddr());
        //区域Id
        taskEntity.setRegionId(vmInfo.getRegionId());

        this.save(taskEntity);

        //如果是补货工单，向 工单明细表插入记录
        if(taskEntity.getProductTypeId() == VMSystem.TASK_TYPE_SUPPLY){
            taskVo.getDetails().forEach(d->{
                TaskDetailsEntity detailsEntity = new TaskDetailsEntity();
                BeanUtils.copyProperties( d,detailsEntity );
                detailsEntity.setTaskId(taskEntity.getTaskId());
                taskDetailsService.save(detailsEntity);
            });
        }

        /**
         * 创建工单的时候, 在redis 给对应的运维/运营人员加分值
         */
        updateTaskZSet(taskEntity, 1);

        return true;
    }


    /**
     * 接收工单 ==> 把工单状态改成进行中
     * @param
     * @return
     */
    @Override
    public Boolean accept(TaskEntity task) {

        if(task.getTaskStatus() != VMSystem.TASK_STATUS_CREATE){
            throw new RuntimeException("工单不是待执行状态");
        }
        task.setTaskStatus(VMSystem.TASK_STATUS_PROGRESS);
        return this.updateById(task);
    }

    /**
     * 取消工单
     * @param task
     * @return
     */
    @Override
    public Boolean cancel(TaskEntity task , CancelTaskViewModel cancelTaskViewModel) {
        //工单状态是已完成或者已取消抛出异常
        if(task.getTaskStatus() == VMSystem.TASK_STATUS_FINISH || task.getTaskStatus() == VMSystem.TASK_STATUS_CANCEL){
            throw new RuntimeException("该工单已取消或已完成,请勿重复操作");
        }
        task.setTaskStatus(VMSystem.TASK_STATUS_CANCEL);
        task.setDesc(cancelTaskViewModel.getDesc());

        /**
         * 创建工单的时候, 在redis 给对应的运维/运营人员加分值
         */
        updateTaskZSet(task, -1);

        return this.updateById(task);
    }

    /**
     * 完成工单
     * @param taskEntity
     * @return
     */
    @Override
    public Boolean complete(TaskEntity taskEntity) {

        if(taskEntity.getTaskStatus() == VMSystem.TASK_STATUS_FINISH){
            throw new RuntimeException("工单已完成");
        }
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_FINISH);

        //如果是投放工单或撤机工单
        if(taskEntity.getProductTypeId()==VMSystem.TASK_TYPE_DEPLOY
                || taskEntity.getProductTypeId()==VMSystem.TASK_TYPE_REVOKE){
            noticeVMServiceStatus(taskEntity);//运维工单封装与下发
        }

        //如果是补货工单---------------------------
        if(taskEntity.getProductTypeId()==VMSystem.TASK_TYPE_SUPPLY){
            noticeVMServiceSupply(taskEntity);
        }

        return this.updateById(taskEntity);
    }


    /**
     * 更新工单量列表
     *
     * @param taskEntity
     * @param score
     */
    private void updateTaskZSet(TaskEntity taskEntity, int score) {

        String roleCode = "1003";//运维员
        if (taskEntity.getProductTypeId().intValue() == 2) {//如果是补货工单
            roleCode = "1002";//运营员
        }

        String key = VMSystem.REGION_TASK_KEY_PREF
                + taskEntity.getCreateTime().format(DateTimeFormatter.ofPattern("yyyyMMdd"))
                + "." + taskEntity.getRegionId() + "." + roleCode;

        redisTemplate.opsForZSet().incrementScore(key, taskEntity.getUserId(), score);
    }

    /**
     * 判断当前机器,是否有同类型,未完成的工单  --> task_status<=2
     * @param innerCode
     * @param productType
     * @return
     */
    private boolean haveTask(String innerCode, int productType) {
        LambdaQueryWrapper<TaskEntity> le = Wrappers.lambdaQuery(TaskEntity.class)
                .eq(TaskEntity::getInnerCode, innerCode)
                .eq(TaskEntity::getProductTypeId, productType)
                .le(TaskEntity::getTaskStatus, VMSystem.TASK_STATUS_PROGRESS);
        System.out.println("le = " + le);
        //返回结果条数大于0,代表已存在
        return this.count(le)>0;
    }

    /**
     * 检查工单是否合法
     */
    private VmVO checkTask(TaskViewModel taskVo) {
        //远程调用获取点位信息
        VmVO vmInfo = vMService.getVMInfo(taskVo.getInnerCode());
        //获取该点位的机器状态
        Integer vmStatus = vmInfo.getVmStatus();
        //机器运营中,发布投放工单,抛出异常
        if(vmStatus == VMSystem.VM_STATUS_RUNNING && taskVo.getProductType() == VMSystem.TASK_TYPE_DEPLOY){
             throw new LogicException("该机器已在运营中,请勿重复部署");
        }

        //机器不在运营中,发布补货工单,抛出异常
        if(vmStatus != VMSystem.VM_STATUS_RUNNING && taskVo.getProductType() == VMSystem.TASK_TYPE_SUPPLY){
            throw new LogicException("该机器未在运营中,无法补货");
        }

        //机器不在运营中,发布撤机工单,抛出异常
        if(vmStatus != VMSystem.VM_STATUS_RUNNING && taskVo.getProductType() == VMSystem.TASK_TYPE_REVOKE){
            throw new LogicException("该机器未在运营中,无法撤机");
        }

        //机器不在运营中,发布维修工单,抛出异常
        if(vmStatus != VMSystem.VM_STATUS_RUNNING && taskVo.getProductType() == VMSystem.TASK_TYPE_REPAIR){
            throw new LogicException("该机器未在运营中,无法维修");
        }
        return vmInfo;
    }

    /**
     *     生成工单编号
     */
    public String createTaskCode() {
        Date date = new Date();
        String time = new SimpleDateFormat("yyyyMMdd").format(date);
        String key = "lkd" + time;

        Object o = redisTemplate.opsForValue().get(key);
        if (o == null) {
            redisTemplate.opsForValue().increment(key, 1);
            Object o1 = redisTemplate.opsForValue().get(key);
            return time + String.format("%04d", (int) o1);
        }

        redisTemplate.opsForValue().increment(key, 1);
        Object o2 = redisTemplate.opsForValue().get(key);
        return time + String.format("%04d", (int) o2);
    }

    /**
     * 运维工单封装与下发
     *
     * @param taskEntity
     */
    private void noticeVMServiceStatus(TaskEntity taskEntity) {
        //向消息队列发送消息，通知售货机更改状态
        //封装协议
        TaskCompleteContract taskCompleteContract = new TaskCompleteContract();
        taskCompleteContract.setInnerCode(taskEntity.getInnerCode());//售货机编号
        taskCompleteContract.setTaskType(taskEntity.getProductTypeId());//工单类型
        //发送到emq
        try {
            mqttProducer.send(TopicConfig.VMS_COMPLETED_TOPIC, 2, taskCompleteContract);
        } catch (Exception e) {
            log.error("发送工单完成协议出错");
            throw new LogicException("发送工单完成协议出错");
        }
    }

    /**
     * 补货协议封装与下发
     *
     * @param taskEntity
     */
    private void noticeVMServiceSupply(TaskEntity taskEntity) {

        //协议内容封装
        //1.根据工单id查询工单明细表
        QueryWrapper<TaskDetailsEntity> qw = new QueryWrapper<>();
        qw.lambda()
                .eq(TaskDetailsEntity::getTaskId, taskEntity.getTaskId());
        List<TaskDetailsEntity> details = taskDetailsService.list(qw);

        //2.构建协议内容
        SupplyContract supplyContract = new SupplyContract();
        supplyContract.setInnerCode(taskEntity.getInnerCode());//售货机编号
        List<SupplyChannel> supplyChannels = Lists.newArrayList();//补货数据
        //从工单明细表提取数据加到补货数据中
        details.forEach(d -> {
            SupplyChannel channel = new SupplyChannel();
            channel.setChannelId(d.getChannelCode());
            channel.setCapacity(d.getExpectCapacity());
            supplyChannels.add(channel);
        });
        supplyContract.setSupplyData(supplyChannels);

        //3.下发补货协议
        //发送到emq
        try {
            mqttProducer.send(TopicConfig.VMS_SUPPLY_TOPIC, 2, supplyContract);
        } catch (Exception e) {
            log.error("发送工单完成协议出错");
            throw new LogicException("发送工单完成协议出错");
        }
    }

}
